import logging
import os
import time

from celery import shared_task
from fabric import Connection
log = logging.getLogger(__name__)
from util.const import bitmex_project_tag, project_logs, project_root, runbitmex_command_prefix
from . models import Account


def start_binance_ws_process(account):
    conn = Connection(
        'localhost',
        connect_kwargs={'key_filename': ['/srv/keys/root_id']})
    # 先update一次，去除掉失效的任务
    conn.run('supervisorctl update')
    result = conn.run('supervisorctl status')
    processes = result.stdout.split('\n')
    running = False
    name = account.name
    for pro in processes:
        log.info(pro)
        if f'{bitmex_project_tag}_account_socket_{name}' in pro:
            log.info(f'{name}程序已经在运行中，不必添加新配置')
            running = True
            break
    if running:
        return
    log.info(f'准备为帐号{name}添加一个新的配置文件来运行websocket程序')

    tpl = f"""[program:{bitmex_project_tag}_account_socket_{name}]
directory={project_root}
command={runbitmex_command_prefix}  {name}
stdout_logfile = {project_logs}/{bitmex_project_tag}_account_socket_{name}.log
stderr_logfile = {project_logs}/{bitmex_project_tag}_account_socket_{name}.log
"""
    df = f'/etc/supervisor/conf.d/{bitmex_project_tag}_account_socket_{name}.conf'
    tmp_file = f'socket_{name}.conf'
    log.info(tpl)
    with open(tmp_file, 'w') as sf:
        sf.write(tpl)
    log.info(f'template file path {os.path.abspath(tmp_file)}')
    conn.put(os.path.abspath(tmp_file), df)
    os.remove(tmp_file)
    conn.run('supervisorctl update')
    # TODO 睡眠一会，检查是否跑起来了。然后再发通知。
    conn.close()
    log.info(f'{name} websocket is running!')


@shared_task
def start_ws_process(account_id):
    """启动帐号对应的websocket进程
    """
    log.info(f'将启动id为{account_id}的websocket进程')
    retry_count = 3
    while retry_count:
        try:
            account = Account.objects.get(pk=account_id)
            break
        except:
            log.error('not found new account, just wait 3 seconds')
            time.sleep(3)
            retry_count -= 1

    if retry_count <= 0:
        raise Exception(f'still not found account which id is {account_id}')
    start_binance_ws_process(account)
    # if account.platform.slug == 'binance':
    #     start_binance_ws_process(account)
    # else:
    #     raise Exception(f'exchange {account.platform.slug} not support yet')


def remove_binance_ws_process(account_name):
    df = f'/etc/supervisor/conf.d/{bitmex_project_tag}_account_socket_{account_name}.conf'
    if not os.path.exists(df):
        log.info('找不到该帐号的Supervisor配置，直接跳出了')
        return
    os.remove(df)
    conn = Connection(
        'localhost',
        connect_kwargs={'key_filename': '/srv/keys/root_id'})
    conn.run('supervisorctl update')
    conn.close()
    log.info(f'成功移除{account_name}的websocket进程')


@shared_task
def remove_ws_process(account_name):
    remove_binance_ws_process(account_name)
    # if account.platform.slug == 'binance':
    #     remove_binance_ws_process(account)
    # else:
    #     raise Exception(f'exchange {account.platform.slug} not support yet')











